package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entyti.Article;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "01.用户模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("login")
    @ApiOperation(value = "登录功能")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session) {
        log.debug("userLoginDTO= {}" ,userLoginDTO);
        String username=userLoginDTO.getUsername();
        String password=userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectLongin(username, password);
        if (userVO!=null){//登录成功
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
    @PostMapping("article")
    @ApiOperation(value = "发表文章功能")
    private JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        log.debug("userArticleDTO={}", userArticleDTO);
   //     log.debug("s"+userVO);
//        if (userVO == null) {//未登录
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        UserVO userVO = (UserVO) session.getAttribute("user");

        article.setUserId(userVO.getId());
        System.out.println(article);
        userMapper.insert(article);
        return JsonResult.ok();
    }
}
